import { delay } from '@wowon/utils';
import { userList } from './access/user';
import {
  access_type,
  getToken,
  updateUser,
  removeUser,
  getCurrentUser,
  signRefreshToken,
  signToken,
} from '../auth-center';

export default {
  /** 获取 token */
  'POST /mock/user/login': async (req, res) => {
    const { username, password } = req.body;
    const user = await userList.profile({ username });
    const data = user.data;
    if (!data) {
      res.json({ code: '1001', message: '用户不存在' });
    } else if (data.enable !== '1') {
      res.json({ code: '1002', message: '访问受限，账号已被禁用' });
    } else if (data.password !== password) {
      res.json({ code: '1003', message: '密码输入错误' });
    } else {
      const refresh_token = signRefreshToken();
      const access_token = signToken(refresh_token, true);

      updateUser(access_token, user);

      res.json({ code: '0', message: '登录成功', access_type, access_token, refresh_token });
    }
  },
  /** 刷新 token */
  'POST /mock/token/refresh': async (req, res) => {
    await delay(200);
    const { refresh_token } = req.body;
    const access_token = signToken(refresh_token);
    if (!access_token) {
      res.json({ code: '-1', message: 'refresh_token 已失效！' });
    } else {
      res.json({ code: '0', message: '成功', access_type, access_token });
    }
  },
  /** 传 token 获取当前用户 */
  'GET /mock/user/current': async (req, res) => {
    await delay(200);
    const user = getCurrentUser(req);
    if (!user) {
      res.statusCode = 401;
      res.json({ code: '-1', message: '用户未登录' });
      return;
    }
    user.data.phone = user.data.phone.replace(/(\d{3}).+(\d{4})/, '$1****$2');
    user.data.password = '******';
    res.json(user);
  },
  /** 退出登录，删除 token 权限 */
  'POST /mock/user/logout': async (req, res) => {
    await delay(200);
    const token = getToken(req);
    removeUser(token);
    res.json({ code: '0', message: '退出成功！' });
  },
  /** 查询登录记录 */
  /** 查询当前在线用户 */
  /** 强制用户 token 失效 */
};
